package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.project_template.entity.SysRole;
import com.demo.project_template.entity.SysRoleMenu;
import com.demo.project_template.mapper.SysRoleMapper;
import com.demo.project_template.service.SysRoleMenuService;
import com.demo.project_template.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.project_template.util.CheckEmptyUtil;
import com.demo.project_template.util.JwtUtil;
import com.demo.project_template.vo.request.sys.SysRoleRequestVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-01-03 20:32:03
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Override
    @Transactional
    public void createOrUpdateSysRole(SysRoleRequestVO sysRoleRequestVO) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRole,sysRoleRequestVO);
        Long userId = JwtUtil.getUserId();
        if (CheckEmptyUtil.isEmpty(sysRoleRequestVO.getId())){
            sysRole.setCreateBy(userId);
        }
        sysRole.setUpdateBy(userId);
        saveOrUpdate(sysRole);
        //添加角色与菜单的关系
        if (!CheckEmptyUtil.isEmpty(sysRoleRequestVO.getId())){
            sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,sysRoleRequestVO.getId()));
        }
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        sysRoleRequestVO.getSysMenuIds().forEach(menuId->{
            sysRoleMenus.add(new SysRoleMenu(sysRole.getId(),menuId));
        });
        sysRoleMenuService.saveBatch(sysRoleMenus);
    }
}
